import FileUtil from "./utils/FileUtil.js";
import Action from "./core/action/Action";
import path from "node:path";

export type ActionLoaderFilterType = (modulePath: string) => boolean;

const actionLoader = {
    load: async function (filter: ActionLoaderFilterType) {
        const files = await FileUtil.getAllFileInDirectory(path.join(__dirname, 'src'))
        if (!files || files.length === 0) {
            throw new Error("No files found.");
        }
        const actionList = []
        for (let file of files) {
            const modulePath = '.' + file.replace(__dirname, '').substring(4).replace(/\\/g, '/')
            if (filter) {
                if (!filter(modulePath)) {
                    continue
                }
            }
            const module = require(file)
            const action = module.action
            if (action && action instanceof Action) {
                actionList.push({
                    name: action.name,
                    path: modulePath
                })
            }
        }
        return `const {ActionMap} = require('../lib/core/ActionMap.js');\n`
            + actionList.map(item => {
                return [
                    `const ${item.name}Action = require('${item.path}');`,
                    `${item.name}Action.action.fun && ${item.name}Action.action.fun(${item.name}Action);`,
                    `ActionMap.add(${item.name}Action.action);`
                ].join('\n')
            }).join('\n');
    }
}

export default actionLoader
